import axios from 'axios';
import querystring from 'querystring';
import {
  Toast,
} from 'mint-ui';
import store from '@/store/index';

const _axios = axios.create({
  baseURL: '/',
  timeout: 6000,
  withCredentials: true
});

_axios.interceptors.request.use(config => {
  if (config.loading) {
    store.commit('app/setRequestCount');
    store.commit('app/setLoadingState', true);
  }
  return config;
}, error => {
  store.commit('app/setLoadingState', false);
  return Promise.reject(error);
});

_axios.interceptors.response.use(response => {
  const {
    config
  } = response
  if (config.loading) {
    store.commit('app/setResponseCount');
  }
  if (store.state.app.requestCount > 0 && store.state.app.requestCount === store.state.app.responseCount) {
    store.commit('app/setLoadingState', false);
    // 重置请求数，响应数
    store.commit('app/resetRequestCount');
    store.commit('app/resetResponseCount');
  }
  if (response.status >= 400 && response.data.errors.length) {
    let message = '';
    response.data.errors.forEach(error => {
      message += `${error.message}\n`;
    });
    return Promise.reject(new Error(`500, axios status > 400 err. ${message}`));
  }
  return response;
}, (error) => {
  store.commit('app/setLoadingState', false);

  let message = `${error.message}`;
  if (error.config) {
    message += `, url: ${error.config.url}`;
  }
  return Promise.reject(new Error(`${message}`));
});

// function checkStatus(response) {
//   // 如果状态码正常，则直接返回数据
//   if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
//     return response;
//   }
//   return {
//     status: -404,
//     msg: '接口请求异常'
//   };
// }

// function checkCode(response) {
//   // 如果code异常，可提示用户错误信息
//   if (response.status === -404) {
//     MessageBox({
//       title: '异常情况',
//       message: response.msg,
//     });
//     return;
//   }

//   return response.data;
// }

export default {
  async request(url, options = {}) {
    const defaultOptions = {
      method: 'get',
      data: {}
    };
    options = {
      ...defaultOptions,
      ...options
    };
    const {
      data
    } = options;
    if (options.method !== 'get') {
      const searchstring = querystring.stringify(data);
      url += searchstring ? `?${searchstring}` : '';
    }

    if (options.method === 'post') {
      options.method = 'post';
      options.headers = {
        'Content-Type': 'application/json;charset=UTF-8'
      };
    }

    const params = {
      url,
      ...options
    };

    return _axios(params)
      .then(response => {
        return response
      })
      .catch(() => {
        Toast('网络异常或接口错误，请稍后重试');
      });
  },

  async post(url, data = {}, options = {}) {
    options.method = 'post';
    options.data = data;
    return this.request(url, options);
  },

  async get(url, data = {}, options = {}) {
    options.data = data;
    return this.request(url, options);
  },

  async postBody(url, data = {}, options = {}) {
    options.method = 'postBody';
    options.data = data;
    options.headers = {
      'Content-Type': 'application/json;charset=UTF-8'
    };
    return this.request(url, options);
  },
};